package com.fwzc.giuseppe.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fwzc.giuseppe.R;
import com.fwzc.giuseppe.Api.Api;
import com.fwzc.giuseppe.base.BaseActivity;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 申请退货
 * 
 * @author llf
 * 
 */
@SuppressLint("InflateParams")
public class ChangeActivity extends BaseActivity implements OnClickListener {
	private Dialog dialog;
	private RelativeLayout choice_photo;
	private Button camera, album, cancel;
	private final static int CAMERA = 101, ALBUM = 100, CROP = 102;
	private int imageCount;
	private final static String TEMP = "phone.jpg";
	private File tempFile;
	private ImageView choice;
	private Button submmit;
	private LinearLayout images;
	private EditText reason;
	
	private int suitId;
	private String userId;
	private String brief, orderNumber, price, imgURL, amount, orderGoodsDetailId;
	private ProgressDialog load;
	private HttpUtils httpUtil;
	private BitmapUtils bitmapUtil;
	private ImageView image;
	private TextView name,order_code,order_price,number;
	private ArrayList<String> imagePath = new ArrayList<String>();
	private ArrayList<File> files = new ArrayList<File>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change);

		initBar();
		initView();
		initClick();
	}

	private void initView() {
		// 网络请求相关
		httpUtil = new HttpUtils();
		bitmapUtil = new BitmapUtils(this);
		load = new ProgressDialog(this);
		load.setMessage(getResources().getString(R.string.deal));
		load.setCancelable(false);
		userId = getSharedPreferences("user", Activity.MODE_PRIVATE).getString(
				"userId", "");
		//头部
		actionbar_side_name.setText("申请换货");
		iv_actionbar_side_left.setVisibility(View.VISIBLE);
		iv_actionbar_side_left.setOnClickListener(this);

		choice_photo = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.choice, null);
		camera = (Button) choice_photo.findViewById(R.id.camera);
		album = (Button) choice_photo.findViewById(R.id.album);
		cancel = (Button) choice_photo.findViewById(R.id.cancel);
		dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(choice_photo);

		choice = (ImageView) findViewById(R.id.choice);
		choice.setOnClickListener(this);
		submmit = (Button) findViewById(R.id.submmit);
		submmit.setOnClickListener(this);
		images = (LinearLayout) findViewById(R.id.images);
		reason = (EditText) findViewById(R.id.reason);
		image = (ImageView)findViewById(R.id.clothes_image);
		name = (TextView)findViewById(R.id.name);
		order_code = (TextView)findViewById(R.id.order_code);
		order_price = (TextView)findViewById(R.id.price);
		number = (TextView)findViewById(R.id.number);
		
		Intent intent = getIntent();
		suitId = intent.getIntExtra("suit_id", -1);
		brief = intent.getStringExtra("brief");
		orderNumber = intent.getStringExtra("orderNumber");
		price = intent.getStringExtra("price");
		amount = intent.getStringExtra("amount");
		imgURL = intent.getStringExtra("imgURL");
		orderGoodsDetailId = intent.getStringExtra("orderGoodsDetailId");
		name.setText(brief);
		order_code.setText(orderNumber);
		order_price.setText(price);
		number.setText(amount);
		BitmapDisplayConfig config = new BitmapDisplayConfig();
		config.setLoadFailedDrawable(getResources().getDrawable(R.drawable.error));
		bitmapUtil.display(image, imgURL, config);
	}

	private void initClick() {
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!Environment.getExternalStorageState().equals(
						android.os.Environment.MEDIA_MOUNTED)) {
					showToast("请插入存储卡再试");
					return;
				} else {
					if (tempFile == null) {
						tempFile = new File(Environment
								.getExternalStorageDirectory(), TEMP);
					}
				}
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(tempFile));
				startActivityForResult(cameraIntent, CAMERA);
			}
		});

		album.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, ALBUM);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_actionbar_side_left:
			finish();
			break;

		case R.id.choice:
			if (imageCount == 3) {
				showToast("最多上传三张照片哦");
				return;
			}

			Window window = dialog.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.mydialog);
			dialog.show();
			window.getDecorView().setPadding(0, 0, 0, 0);
			WindowManager.LayoutParams params = window.getAttributes();
			params.width = WindowManager.LayoutParams.MATCH_PARENT;
			params.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(params);
			break;

		case R.id.submmit:
			if ("".equals(reason.getText().toString())) {
				showToast("请填写换货理由");
				return;
			}
			sendRequest();
			break;
		default:
			break;
		}
	}
	
	private void sendRequest(){
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("userId", userId);
		params.addBodyParameter("suitId", String.valueOf(suitId));
		params.addBodyParameter("orderId", orderNumber);
		params.addBodyParameter("orderGoodsDetailId", orderGoodsDetailId);
		params.addBodyParameter("type", "5");
		params.addBodyParameter("contents", reason.getText().toString());
		//还要加上传图片
		for (int i = 0; i < files.size(); i++) {
			params.addBodyParameter(imagePath.get(i),files.get(i));
		}
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.ORDER_REFUND,
				params, new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("上传失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(responseStr.result);
							int resultCode = response.getInt("resultCode");
							if(resultCode == 0){
								load.dismiss();
								showToast("上传成功");
								for (int i = 0; i < files.size(); i++) {
									files.get(i).delete();
								}
							}else{
								load.dismiss();
								showToast(response.get("msg"));
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}
					}
				});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == ALBUM && resultCode == RESULT_OK && data != null) {
			Uri uri = data.getData();
			crop(uri);
		}

		if (requestCode == CAMERA && resultCode == RESULT_OK) {
			crop(Uri.fromFile(tempFile));
		}

		if (requestCode == CROP && resultCode == RESULT_OK && data != null) {
			Bitmap bitmap = data.getParcelableExtra("data");
			saveMyBitmap(bitmap);
			imageCount++;
			ImageView imageView = new ImageView(ChangeActivity.this);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					(int)getResources().getDimension(R.dimen.image_bold),
					(int)getResources().getDimension(R.dimen.image_bold));
			lp.setMargins(0, 0, 20, 0);
			imageView.setLayoutParams(lp);
			imageView.setImageBitmap(bitmap);
			images.addView(imageView);
			try {
				tempFile.delete();
			} catch (Exception e) {
				// 没有建过零时文件
			}
			dialog.dismiss();
		}
	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", getResources().getDimension(R.dimen.image_bold));
		intent.putExtra("outputY", getResources().getDimension(R.dimen.image_bold));

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, CROP);
	}

	private void saveMyBitmap(Bitmap mBitmap){
		  File f = new File(Environment.getExternalStorageDirectory(), (imageCount+TEMP));
		  files.add(f);
		  imagePath.add(f.getPath());
		  try {
		   f.createNewFile();
		  } catch (IOException e) {
			  
		  }
		  FileOutputStream fOut = null;
		  try {
		   fOut = new FileOutputStream(f);
		  } catch (FileNotFoundException e) {
		   e.printStackTrace();
		  }
		  mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		  try {
		   fOut.flush();
		  } catch (IOException e) {
		   e.printStackTrace();
		  }
		  try {
		   fOut.close();
		  } catch (IOException e) {
		   e.printStackTrace();
		  }
		 }
}
